package com.appbee.lyrdb.client.presenter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import com.appbee.core.client.listener.ISearchListener;
import com.appbee.core.client.ui.ISimpleFilterView;
import com.appbee.lyrdb.shared.LyrSongProxy;
import com.appbee.songs.shared.SongRequestFactory;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;

public class LyricDataProvider extends AsyncDataProvider<LyrSongProxy> implements ISearchListener
{
	private final SongRequestFactory requestFactory;
	private ISimpleFilterView filterView;
	
	@Inject
	public LyricDataProvider(SongRequestFactory requestFactory)
	{
		super();
		this.requestFactory = requestFactory;
	}

	public ISimpleFilterView getFilterView()
	{
		return filterView;
	}

	public void setFilterView(ISimpleFilterView filterView)
	{
		this.filterView = filterView;
	}

	@Override
	protected void onRangeChanged(HasData<LyrSongProxy> display)
	{
		if(filterView!=null && filterView.getSearchValue().length()>0)
		{
			Request<List<LyrSongProxy>> request = requestFactory
					.getLyrDbService().findByFullt(filterView.getSearchValue());
			request.fire(new Receiver<List<LyrSongProxy>>()
			{

				@Override
				public void onSuccess(List<LyrSongProxy> response)
				{
					updateRowCount(response.size(), true);
					updateRowData(0, response);
				}
				
			});
		}
		else
		{
			updateRowCount(0, true);
			updateRowData(0, new ArrayList<LyrSongProxy>());
		}
	}

	

	@Override
	public void onSearch()
	{
		if(filterView!=null && filterView.getSearchValue().length()>0)
		{
			Request<List<LyrSongProxy>> request = requestFactory
					.getLyrDbService().findByFullt(filterView.getSearchValue());
			request.fire(new Receiver<List<LyrSongProxy>>()
			{

				@Override
				public void onSuccess(List<LyrSongProxy> response)
				{
					updateRowCount(response.size(), true);
					updateRowData(0, response);
				}
				
			});
		}
		else
		{
			updateRowCount(0, true);
			updateRowData(0, new ArrayList<LyrSongProxy>());
		}
	}

}
